$(function(){
    $("#validate_code").on("input propertychange",function () {
        validateText.controlBtnValidate();
    });
    $("#mail").on("change",function () {
        validateText.controlBtnValidate();
        validateText.checkEmail();
    });
    $("#confirm-pwd").on("change",function () {
        validateText.controlBtnValidate();
        validateText.checkConfirmPwd();
    });
    $("#new-pwd").on("change",function () {
        validateText.controlBtnValidate();
        validateText.checkNewPwd();
        if ($("#confirm-pwd").val().trim().length>0) {
            validateText.checkConfirmPwd();
        }
    });
    $("#btn-reset").on("click",function () {
        if ($("#btn-validate").text() != ""){
            $("#btn-validate").attr("disabled",true);
            return;
        }
        if ($("#btn-update").text() != ""){
            $("#btn-update").attr("disabled",true);
        }
    });
    /**
     * 发送验证码的点击事件
     */
    $("#mail_code_btn").on("click",function () {
        //判断邮箱格式
        if (!validateText.checkEmail()) {
            return;
        }
        //let url = $("base").href + "\/send-mail-code/";
        let location = (window.location+'').split('/');
        let basePath = location[0]+'//'+location[2]+'/'+location[3];
        let url = basePath + "\/send-mail-code/";
        let dataJson = {"mail":$("#mail").val().trim().toLowerCase()};
        $.ajax({
            headers : {
                'Accept' : 'application/json',
                'Content-Type' : 'application/json'
            },
            type : "POST",
            url : url,
            data : JSON.stringify(dataJson),
            success : function(message, tst, jqXHR) {
                if (!util.checkSessionOut(jqXHR)){ return false;}
                if (message.result == "success") {
                    //禁用验证码发送按钮
                    $("#mail_code_btn").attr("disabled",true);
                    util.success(message.messageInfo, function() {
                        //其他操作
                    });
                } else if (message.result == "fail") {
                    util.notify(message.messageInfo);
                } else {
                    util.error("操作失败请稍后尝试");
                }
            },
            error : function(jqXHR, textStatus) {
                util.error("操作失败请稍后尝试");
            }
        });
    });
    /**
     * 提交邮箱验证码
     */
    $("#btn-validate").on("click",function(){
        let $validateCode = $("#validate_code").val().trim();
        if($validateCode.length<2 || $validateCode.length>10){
            //$("#validate_code").next().text("验证码错误！");
            util.notify("验证码错误！");
            return;
        }
        let location = (window.location+'').split('/');
        let basePath = location[0]+'//'+location[2]+'/'+location[3];
        let url = basePath + "\/validate-mail-code/";
        let dataJson = {
            "mail":$("#mail").val().trim().toLowerCase(),
            "validate_code" :$validateCode
        };
        $.ajax({
            headers : {
                'Accept' : 'application/json',
                'Content-Type' : 'application/json'
            },
            type : "POST",
            url : url,
            data : JSON.stringify(dataJson),
            success : function(message, tst, jqXHR) {
                if (!util.checkSessionOut(jqXHR)){ return false;}
                if (message.result == "success") {
                    validateText.afterCheckMail();
                    util.success(message.messageInfo, function() {
                        $("#validate_code").next().text("");
                    });
                } else if (message.result == "fail") {
                    util.notify(message.messageInfo);
                } else {
                    util.error("操作失败请稍后尝试");
                }
            },
            error : function(jqXHR, textStatus) {
                util.error("操作失败请稍后尝试");
            }
        });
    });

    let validateText = {
        /**
         * 邮箱验证成功后，修改密码前的变化
         */
        afterCheckMail : function () {
            $(".form-mail").css('display','none');
            $(".form-code").css('display','none');
            //1、禁用邮箱框、验证码框和验证码按钮
            $("#validate_code").attr("disabled",true);
            $("#mail").attr("disabled",true);
            $("#mail_code_btn").attr("disabled",true);

            //2、显示两个密码框
            $("#div-confirm-pwd").css({"display":"inline"});
            $("#div-new-pwd").css({"display":"inline"});
            $("#btn-validate").off("click");
            $("#btn-validate").attr("id","btn-update");
            $("#btn-update").attr("disabled",true);

            $(".default-sidenav").children(":first").next().attr("class","active");
            $(".default-sidenav").children(":first").attr("class","");
            bindUpdatePwdByMail();
        },
        checkEmail : function () {
            let $email = $("#mail").val().trim().toLowerCase();
            let $mailMsg = $("#mail").next();
            if ($email == "") {
                $mailMsg.text("邮箱不能为空");
                return false;
            }
            if ($email.length > 60 || $email.length < 9) {
                $mailMsg.text("请保持在9-60个字符以内");
                return false;
            }
            const reg = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            if (!reg.test($email)) {
                $mailMsg.text("无效的邮箱");
                return false;
            }
            $mailMsg.text("");
            return true;
        },
        checkNewPwd : function (){
            //1、检测密码的格式
            const $newPwd = $("#new-pwd").val().trim();
            if($newPwd.length > 10 || $newPwd.length <6){
                $("#new-pwd").next().text("长度请保持在6到10之间！");
                return false;
            };
            $("#new-pwd").next().text("");
            return true;
        },
        checkConfirmPwd : function (){
            const $confirmPwd = $("#confirm-pwd").val().trim();
            let $confirmPwdNext = $("#confirm-pwd").next();
            if($confirmPwd.length > 10 || $confirmPwd.length <6){
                $confirmPwdNext.text("长度请保持在6到10之间！");
                return false;
            }
            $("#confirm-pwd").next().text("");
            //2、比对密码的一致性
            if($("#new-pwd").val().trim() != $confirmPwd){
                $confirmPwdNext.text("两次密码不一致！");
                return false;
            }
            $confirmPwdNext.text("");
            return true;
        },
        /**
         * 控制“确认”按钮是否可操作
         */
        controlBtnValidate : function () {
            if( $("#div-new-pwd").css("display") == "none"){
                if($("#validate_code").val().length > 1 && $("#mail_code_btn").prop("disabled") && $("#mail").val().trim().length>0){
                    $("#btn-validate").attr("disabled",false);
                } else {
                    $("#btn-validate").attr("disabled",true);
                }
                return;
            }

            if($("#new-pwd").val().trim().length > 0 && $("#confirm-pwd").val().trim().length>0){
                $("#btn-update").attr("disabled",false);//可操作
            } else {
                $("#btn-update").attr("disabled",true);//不可操作
            }

        }
    };

    /**
     * 绑定点击发
     */
    function bindUpdatePwdByMail() {
        /**
         * 发送修改密码的请求
         */
        $("#btn-update").on("click", function(){
            //判断密码
            if(!validateText.checkNewPwd() || !validateText.checkConfirmPwd()){
                return;
            }
            let location = (window.location+'').split('/');
            let basePath = location[0]+'//'+location[2]+'/'+location[3];
            let url = basePath + "\/update-pwd-by-mail\/";
            let user = {
                "email":$("#mail").val().trim().toLowerCase(),
                "password" : $("#new-pwd").val().trim()
            };
            $.ajax({
                headers : {
                    'Accept' : 'application/json',
                    'Content-Type' : 'application/json'
                },
                type : "POST",
                url : url,
                data : JSON.stringify(user),
                success : function(message, tst, jqXHR) {
                    if (!util.checkSessionOut(jqXHR)){ return false;}
                    if (message.result == "success") {
                        util.success(message.messageInfo, function() {
                            $("#btn-update").attr("disabled","true");
                            window.location.href = basePath + "\/user-login-page\/";
                        });
                    } else if (message.result == "fail") {
                        util.notify(message.messageInfo);
                    } else {
                        util.error("操作失败请稍后尝试");
                    }
                },
                error : function(jqXHR, textStatus) {
                    util.error("操作失败请稍后尝试");
                }
            });
        });
    }
});